package com.bookkeeping.bookkeepingapi.service;

import com.bookkeeping.bookkeepingapi.model.BookKeep;
import com.bookkeeping.bookkeepingapi.model.User;
import com.bookkeeping.bookkeepingapi.repository.BookKeepRepository;
import com.bookkeeping.bookkeepingapi.repository.UserRepository;
import com.bookkeeping.bookkeepingapi.service.dto.BookKeepDto;
import com.bookkeeping.bookkeepingapi.web.vm.BookKeepVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class BookKeepService {
    @Autowired
    BookKeepRepository bookKeepRepository;

    @Autowired
    UserRepository userRepository;

    @Transactional
    public BookKeep create(BookKeepVM bookKeepVM, User user){
        BookKeep bookKeep = new BookKeep(bookKeepVM, user);
        bookKeep = bookKeepRepository.save(bookKeep);
        user.setCount(user.getCount()+1);
        userRepository.save(user);
        return bookKeep;
    }

    @Transactional
    public BookKeep update(BookKeep bookKeep,BookKeepVM bookKeepVM){
        bookKeep.setBookKeepDate(bookKeepVM.getBookKeepDate());
        bookKeep.setYear(bookKeepVM.getBookKeepDate().getYear());
        bookKeep.setMonth(bookKeepVM.getBookKeepDate().getMonthValue());
        bookKeep.setType(bookKeepVM.getType());
        bookKeep.setCagegory(bookKeepVM.getCagegory());
        bookKeep.setPrice(bookKeepVM.getPrice());
        bookKeep.setRemark(bookKeepVM.getRemark());
        bookKeep.setUpdateTime(LocalDateTime.now());
        return bookKeepRepository.save(bookKeep);
    }

    @Transactional
    public void delete(BookKeep bookKeep) {
        bookKeepRepository.delete(bookKeep);
    }
}
